// pages/tickets/tickets.js
import request from "../../utils/request.js";
const themeManager = require("../../utils/theme.js");

Page(themeManager.enhancePage({
  data: {
    tickets: [],
    filteredTickets: [],
    loading: true,
    statusFilter: "all",
    currentTheme: 'dark', // 添加主题状态
  },

  onShow: function() {
    this.loadTickets();
  },

  loadTickets(status = null) {
    // 构建API URL，添加状态筛选参数
    let url = "/tickets/my_tickets";
    if (status && status !== "all") {
      // 将状态字符串转换为对应的数字
      const statusMap = {
        "pending": 0, // 未处理
        "wait-user": 1, // 等待管理员响应
        "wait-admin": 2, // 等待管理员响应
        "completed": 3, // 已结单
      };
      const statusCode = statusMap[status];
      if (statusCode !== undefined) {
        url += `?status=${statusCode}`;
      }
    }

    request
      .get(url)
      .then((res) => {
        if (res) {
          this.setData({
            tickets: res.data.items,
            filteredTickets: res.data.items, // 直接使用API返回的数据
            loading: false,
          });
        } else {
          this.setData({
            tickets: [],
            filteredTickets: [],
            loading: false,
          });
        }
      })
      .catch((err) => {
        console.error("加载工单列表失败:", err);
        this.setData({
          tickets: [],
          filteredTickets: [],
          loading: false,
        });
        wx.showToast({
          title: "加载失败，请重试",
          icon: "error",
        });
      });
  },

  // 切换状态筛选
  changeStatusFilter(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      statusFilter: status,
    });

    // 重新从API加载数据
    this.loadTickets(status);
  },

  // 创建工单
  createTicket() {
    wx.navigateTo({
      url: "/pages/create_ticket/tickets",
    });
  },

  // 跳转到工单详情
  goToTicketDetail(e) {
    const ticket = e.currentTarget.dataset.ticket;
    wx.navigateTo({
      url: `/pages/ticket/ticket?ticketId=${ticket.uuid}`,
    });
  },
}));
